<?php

namespace App\Http\Controllers\Machine;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Models\Refund\RefundSignTotalModel;
use App\Models\UserModel;
use App\Utils\ApiResponse;
use App\Utils\ControllerModelTrait;
use App\Utils\VerifyRequestInput;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class RefundSignTotalController extends Controller
{
    use ApiResponse, VerifyRequestInput, ControllerModelTrait;

    /**
     * 获取列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getList(Request $request): JsonResponse
    {
        $Model = new RefundSignTotalModel();
        if ($request->input('sid'))
            $Model = $Model->where('sid', $request->input('sid'));
        $pagination = $Model->orderByDesc('id')->paginate(20);
        $items = $this->getItems($pagination->items());
        $sum = $request->input('page') == 1 ? $Model->sum('total') : 0;
        return $this->success([
            'total'  => $pagination->total(),
            'page'   => $pagination->currentPage(),
            'list'   => $items,
            'sum'    => $sum
        ]);
    }

    /**
     * 保存数据
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doSave(Request $request): JsonResponse
    {
        $this->verifyId('sid');
        $total = $this->verifyNumeric('total');
        $data = $request->only(['sid', 'total', 'remark', 'date']);
        if (intval($total) == 0)
            return $this->fail([400900, '请确认登记金额，金额不能为0']);
        if ($request->input('uid'))
            $data['doned_uid'] = $request->input('uid');
        if (!$request->input('date'))
            $data['date'] = Carbon::today()->toDateString();
        $this->saveData(new RefundSignTotalModel(), $data);
        return $this->success();
    }

    /**
     * 获取格式化数据
     * @param $items
     * @return mixed
     */
    private function getItems($items): mixed
    {
        $itemsData = json_decode(json_encode($items), true);
        $users = UserModel::where('role', 'daifa')->pluck('username', 'id');
        if ($itemsData) {
            $supplyCollection = \App\Http\Controllers\Api\SupplyController::getAllSupplyCache();
            $supplyData = $supplyCollection->pluck('CName', 'ID')->toArray();
            $data = [];
            foreach ($itemsData as $item) {
                $sid = $item['sid'];
                $item['username'] = $users[$item['doned_uid']] ??
                $item['sname'] = $supplyData[$sid] ?? '';
                $data[] = $item;
            }
            return $data;
        }
        return $itemsData;
    }
}
